package com.responsemeasure;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;

import com.responsemeasure.help.CustomDialog;

public class FourOfNine extends Activity {
	/** Called when the activity is first created. */
	int[][] ButArray = new int[10][4]; // buttons with colors
	// 1 color, 2 order activated, 3 order selected, 4 time in ms
	ImageButton[] buttons = new ImageButton[9]; // the buttons
	Button resetButton;
	Button exit_btn;
	Button help_btn;
	private static final int HELP_DIALOG = 1;
	private static final int ABOUT_DIALOG = 2;
	int clickCount; // number of clicks by users
	int wrong; // number of wrong choices by user
	int correct; // number of correct choices by user
	final int activeButtons = 4; // max buttons hardcode for now
	long startTime;
	long endTime;
	long prevTime;
	long subTotal;
    private static long intervals[]=new long[4];
	boolean running = false;

	long userId;
	long actionId;
	long testId;
	DRMApplication drmApplication;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fourofnine);
		getParameters();

		drmApplication = (DRMApplication) this.getApplication();

		buttons[0] = (ImageButton) findViewById(R.id.button1);
		buttons[1] = (ImageButton) findViewById(R.id.button2);
		buttons[2] = (ImageButton) findViewById(R.id.button3);
		buttons[3] = (ImageButton) findViewById(R.id.button4);
		buttons[4] = (ImageButton) findViewById(R.id.button5);
		buttons[5] = (ImageButton) findViewById(R.id.button6);
		buttons[6] = (ImageButton) findViewById(R.id.button7);
		buttons[7] = (ImageButton) findViewById(R.id.button8);
		buttons[8] = (ImageButton) findViewById(R.id.button9);

		
		resetButton = (Button) findViewById(R.id.resetButton);
		
		clear();
		
		
		buttons[0].setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ticClick(0);
			}
		});
		buttons[1].setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ticClick(1);
			}
		});
		buttons[2].setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ticClick(2);
			}
		});
		buttons[3].setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ticClick(3);
			}
		});
		buttons[4].setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ticClick(4);
			}
		});
		buttons[5].setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ticClick(5);
			}
		});
		buttons[6].setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ticClick(6);
			}
		});
		buttons[7].setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ticClick(7);
			}
		});
		buttons[8].setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ticClick(8);
			}
		});
		resetButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				reset();
			}
		});

	} // end onCreate

	private void reset() {
		clickCount = 0;
		wrong = 0;
		correct = 0;
		subTotal = 0;
		for (int i = 0; i < 9; i++) {
			ButArray[i][0] = 0;
			ButArray[i][1] = 0;
			ButArray[i][2] = 0;
			ButArray[1][3] = 0;
			buttons[i].setImageResource(R.drawable.graysquare);
		}
		// buttons[9].setImageResource(R.drawable.startbutton100);

		generateTest();
		startTime = System.currentTimeMillis();
		
		//testId = FourOfNine.this.drmApplication.getDataHelper().insertTest(userId, actionId);
		
		running = true;
		resetButton.setText(this.getString(R.string.running));
		return;
	} // end reset

	public void myClickHandler (View v) {
		switch (v.getId()) {
			case R.id.helpButton:
				FourOfNine.this.showDialog(HELP_DIALOG);
				break;
			case R.id.logo:
				FourOfNine.this.showDialog(ABOUT_DIALOG);		
				break;
			case R.id.homeButton:
				finish();
				break;
			default:
				break;
		}
}
	
	private void clear(){ // like reset but leaves gray and not running
		for (int i = 0; i < 9; i++) {
			buttons[i].setImageResource(R.drawable.graysquare);
		}	
		running = false;
		resetButton.setText(this.getString(R.string.start));
	} // end clear
	
	private void generateTest() {
		int rand;
		for (int i = 0; i < activeButtons; i++) {
			rand = (int) Math.round(Math.random() * 8.0);
			while (ButArray[rand][0] == 1) {
				rand = (int) Math.round(Math.random() * 8.0);
			} // end while
			ButArray[rand][0] = 1;
			ButArray[rand][1] = i;
			if (i == 0)
				buttons[rand].setImageResource(R.drawable.bluesquare);
			if (i == 1)
				buttons[rand].setImageResource(R.drawable.greensquare);
			if (i == 2)
				buttons[rand].setImageResource(R.drawable.yellowsquare);
			if (i == 3)
				buttons[rand].setImageResource(R.drawable.blacksquare);
			if (i == 4)
				buttons[rand].setImageResource(R.drawable.whitesquare);
			// SystemClock.sleep(1000);
		}// end for loop
	}// end gen test

	public void ticClick(int b) { // come here on each click
		if ((clickCount < activeButtons)&&(running == true)) { // check done
			if (ButArray[b][0] != 0) { // if not empty correct
				ButArray[b][0] = 0;
				ButArray[b][2] = clickCount;
				buttons[b].setImageResource(R.drawable.graysquare);
				correct += 1;
				
			} else {// empty uncolored square was selected
				if (ButArray[b][2] != 0) {
					ButArray[b][2] = clickCount;
				} // record wrong hit
				buttons[b].setImageResource(R.drawable.redsquare);
				wrong += 1;
			}
			ButArray[b][3] = (int) (System.currentTimeMillis() - startTime);
			long interval = 0;
			if (clickCount == 0) {
				interval = (System.currentTimeMillis() - startTime);
			} else {
				interval = (System.currentTimeMillis() - prevTime);
			}
			prevTime = System.currentTimeMillis();
			subTotal += interval;
			intervals[clickCount]=interval;
			clickCount += 1;
			
		} // end if
		if (clickCount >= activeButtons) {
			if (running == true) {
				endTime = System.currentTimeMillis();
				double avarageTime = subTotal * 1.0 / activeButtons;
				// this is the only place that the DB should be updated.
				// check to see if valid test; not valid if to fast or too slow
				if((subTotal >100)&&(subTotal<10000)){
				  // create a new Row in DB with new testID
				  testId = FourOfNine.this.drmApplication.getDataHelper().insertTest(userId, actionId);
				  // add the data
				  for(int i=0;i<activeButtons;i+=1){
				    FourOfNine.this.drmApplication.getDataHelper().insertResponse(
				      testId, Double.valueOf(intervals[i]));
				    }		
			      // add final data for the test
				  FourOfNine.this.drmApplication.getDataHelper().updateTest(
				    avarageTime, subTotal, correct, clickCount - correct, testId);
			  	  // end of adding data to DB
				} // endif valid test
				else{
					Context context = getApplicationContext();
					Toast.makeText(context,"Bad Test", 2000).show();
				}// endelss 
				running = false;
			}// end if runningTrue
			
			// when done reset button to show start.
			resetButton.setText(this.getString(R.string.start));
			
		}
		return;
	} // end ticClick

	// private void do_exit(){finish();}
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "Reset Measure");
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		reset();
		return true;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

	}

	private void getParameters() {
		Intent i = getIntent();
		Bundle b = i.getExtras();
		this.userId = b.getLong("userId");
		this.actionId = b.getLong("actionId");
	}
	
    public Dialog onCreateDialog(int dialogId) {
    	Dialog dialog = null;
    	switch (dialogId) {
	    	case HELP_DIALOG :
				CustomDialog.Builder customBuilder = new
				CustomDialog.Builder(FourOfNine.this);
				customBuilder.setMessage(R.string.FourOfNineHelpMsg)
					.setPositiveButton("Close", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
	            dialog = customBuilder.create();
	    		break;
	    	case ABOUT_DIALOG : 
				CustomDialog.Builder aboutBuilder = new
				CustomDialog.Builder(FourOfNine.this);
				aboutBuilder.setMessage(R.string.AboutMsg)
					.setPositiveButton("Close", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
	            dialog = aboutBuilder.create();
	    		break;
    	}
    	return dialog;
    }
  
} // end measure java class